<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="部门名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryDepartment">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="Depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="编号" width="200" sortable>
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="200"  sortable>
			</el-table-column>
			<el-table-column prop="employee.username" label="管理员" width="200" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="200" :formatter="formatSex" sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='-1'" style="color: red">禁用</span>
          <span v-if="scope.row.state=='0'" style="color: green">正常</span>
        </template>
			</el-table-column>
			<el-table-column prop="department.name" label="上级部门" min-width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title= "title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="部门姓名" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="管理员" >
          <el-select v-model="editForm.manager_id" placeholder="请选择">
            <el-option  v-for="item in employees" :key="item.id" :label="item.username" :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">正常</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="上级部门">
<!--      <el-input v-model="editForm.parent_id" auto-complete="off"></el-input>-->
          <div class="block">
            <el-cascader
                v-model="editForm.department"
                :options="options"
                :props="{ checkStrictly: true,
                          value:'id',
                          label:'name'
                        }"
                clearable></el-cascader>
          </div>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
    </el-dialog>
	</section>
</template>

<script>

	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
        //员工数据
        employees:[],
				Depts: [],
        options:[],
				total: 0,
        pageSize: 5,
				page: 1,
				listLoading: false,
        title:"",
				sels: [],//列表选中列
				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				editForm: {
					id: 0,
          sn:"",
					name: '',
          manager_id:"",
          dirPath:"",
          state: 0,
          department: '',
				},
			}
		},
		methods: {
      //性别显示转换
      formatSex: function (row, column) {
        return row.state == 0 ? '启用' : '禁用';
      },
      handleCurrentChange(val) {
        this.page = val;
        this.getDepts();
      },
      queryDepartment(){
        this.page = 1
        this.getDepts()
      },
      //获取用户列表
      getDepts() {
        let para = {
          currentPage: this.page,
          keyword: this.filters.keyword,
          pageSize: this.pageSize
        };
        this.listLoading = true;
        this.$http.post("/dept/pageList", para).then(res => {
          this.total = res.data.total;
          this.Depts = res.data.data;
          this.listLoading = false;
        })
      },
      //删除
      handleDel(row) {
        //1.删除的确认框
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {//确认删除的按钮
          this.listLoading = true;
          this.$http.delete("/dept/department/" + row.id).then(res => {
            this.listLoading = false;
            if (res.data.success) {
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
            } else {
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }
            //重新加载数据
            this.getDepts();
          })
        }).catch(() => {//取消删除回调函数
          this.$message('已取消删除');
        })
      },
      //显示编辑界面
      handleEdit: function (index, row) {
        //重置表单
        this.resetForms()
        //查询员工数据
        this.employeeQuery()
        //查询树
        this.deptTreeQuery()
        this.title = "编辑",
        this.editFormVisible = true;
        this.editForm = Object.assign({}, row);
        //编辑回显上级部门
        if(this.editForm.dirPath){
          var dir =  this.editForm.dirPath.split("/")// /65/66/67   "" "65" "66" "67"
          var path = []
          for (let i = 1; i < dir.length-1; i++) {
            //将字符串转为int类
            path.push(parseInt(dir[i]))
          }
        }
        this.editForm.department = path
      },
      //显示新增界面
      handleAdd: function () {
        //重置表单
        this.resetForms()
        //查询员工数据
        this.employeeQuery()
        //查询树
        this.deptTreeQuery()
        this.title = "新增",
        this.editFormVisible = true;
        this.editForm = {
          sn:"",
          name: '',
          manager_id:"",
          dirPath:"",
          state: 0,
          department: [],
        };
      },
      //编辑
      editSubmit: function () {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true;
              let para = Object.assign({}, this.editForm);
              if(para.department){//有值
                //将数组转为对象
                para.parent_id = para.department[para.department.length - 1]
                para.department = null
              }
              this.$http.put("/dept/department",para).then(res =>{
                  this.editLoading = false;
                if (res.data.success) {
                  this.$message({
                    message: res.data.msg,
                    type: 'success'
                  });
                } else {
                  this.$message({
                    message: res.data.msg,
                    type: 'error'
                  });
                }
                //重新加载数据
                this.getDepts();
              })
            });
            this.editFormVisible = false;
          }
        });
      },
      //新增
      addSubmit: function () {
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.addLoading = true;
              //NProgress.start();
              let para = Object.assign({}, this.addForm);
              para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
              addDept(para).then((res) => {
                this.addLoading = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['addForm'].resetFields();
                this.addFormVisible = false;
                this.getDepts();
              });
            });
          }
        });
      },
      selsChange: function (sels) {
        this.sels = sels;
      },
      //批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/dept/batchDelete",ids).then(res => {
            this.listLoading = false;
            if (res.data.success) {
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
            } else {
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }
            //重新加载数据
            this.getDepts();
          })
        }).catch(() => {//取消删除回调函数
          this.$message('已取消删除');
        })
      },
    //查询所有的员工数据
    employeeQuery:function (){
      this.$http.get("/emp/employee").then(res=>{
        this.employees = res.data
      })
    },
    deptTreeQuery: function (){
      this.$http.get("/dept/deptTree").then(res=>{
        this.options = res.data
      })
    },
    resetForms: function (){
       if(this.$refs['editForm']){
       this.$refs['editForm'].resetFields();//重置表单验证
        }
      },
  },

		mounted() {
			this.getDepts();
		}
	}

</script>

<style scoped>

</style>